package client.gui.ingame;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.util.ArrayDeque;
import java.util.Deque;

import lib.Commands;
import lib.Config;
import client.Client;
import client.TCPClientListener;

public class GraphicalChatInterface implements Client {

	/**
	 * 
	 */
	private TCPClientListener listener;
	private Deque<String> log = new ArrayDeque<String>();
	private String msg = "";

	int xRes;
	int yRes;
	protected boolean chatting = false;
	int progress=0;
	String progressmsg="";
	public GraphicalChatInterface(String host, int port, String login,
			int xRes, int yRes) {

		this.xRes = xRes;
		this.yRes = yRes;
		try {
			listener = new TCPClientListener(this, host, port);
		} catch (Exception e) {
			e.printStackTrace();
		}
		listener.start();
		listener.send(Commands.LOGIN, login);

	}

	public GraphicalChatInterface(TCPClientListener listener, int xRes, int yRes) {
		this.listener = listener;
		listener.client.add(this);
		this.xRes = xRes;
		this.yRes = yRes;
	}

	public void displayMessage(String msg) {
		log.push(msg);
		if (log.size() >= 20)
			log.pollLast();
	}

	public void send() {
		if (msg.indexOf("/") == 0)
			listener.send(msg.substring(1));
		else if (!msg.equals(""))
			listener.send(Commands.SEND, msg);
	}

	public void draw(Graphics2D g) {
		if(progress!=0){
			g.setColor(Config.fontColor);
			g.setFont(new Font("Space Age", Font.BOLD, 40));
			g.drawString(progressmsg+" " +progress+"%", 0, yRes/2);
			g.setFont(Config.spaceFont);		
			progressmsg="";
			progress=0;
		}
		int dx=xRes/30*8;
		int xOffset = xRes - xRes / 30 - dx;
		int yOffset = yRes - yRes / 5 - 20;
		int count = 0;

		// chat input
		if (chatting) {
			g.setColor(new Color(100, 100, 100, 150));
			g.fillRect(xOffset, yOffset + yRes / 5 + 2, dx, 20);

			g.setColor(new Color(200, 200, 200, 255));
			g.drawString(msg, xOffset, yOffset + yRes / 5 + 12);
		}

		g.setColor(new Color(10, 10, 10, 150));
		g.fillRect(xOffset, yOffset, dx, yRes / 5);

		g.setColor(new Color(200, 200, 200, 255));
		for (String s : log) {
			if (count > 9)
				return;
			g.drawString(s, xOffset, yOffset + yRes / 5 - count++ * 15 - 3);
		}
	}

	public void exit() {
		listener.listenerStop();
		listener.client.remove(this);

	}

	public void appendMsg(char keyChar) {
		if (keyChar == '\b')
			msg = msg.substring(0, msg.length() - 1);
		else
			msg += keyChar;
	}

	public void resetMsg() {
		msg = "";

	}

	public void send(Commands cmd, String msg) {
		// TODO Auto-generated method stub

	}
	public void displayInfo(Deque<String> msg) {
		displayMessage(listener.getMessage(msg));		
	}

	
	public void progress(String msg,int i) {
		progressmsg=msg;
		progress=i;		
	}

	public void list(Deque<String> msg) {	
	}
}
